package user

import (
	"errors"
	"fmt"
	"kubeInstall/pkg/client/db"
	"kubeInstall/server/models/user"
	"kubeInstall/utils"
	"kubeInstall/utils/uuid"
)

func GetUser(userId string) (*user.User, error) {
	var u user.User

	err := db.Db.Where("user_id = ?", userId).First(&u).Error

	if err != nil {
		if err == db.ErrRecordNotFound {
			return nil, fmt.Errorf("user ID %s not found", userId)
		}
		return nil, err
	}

	//user.Password = ""
	return &u, nil
}

func ListUsers(limit, Offset int) ([]user.User, error) {
	var userList []user.User
	if limit == 0 {
		limit = 10
	}
	err := db.Db.Select("*").Limit(limit).Offset((Offset - 1) * limit).Find(&userList).Error

	if err != nil {
		return userList, err
	}

	for i := range userList {
		user := &userList[i]
		user.Password = ""
	}

	return userList, nil
}

func DeleteUser(userId string) error {
	var u user.User
	err := db.Db.Where("user_id = ?", userId).Delete(&u).Error
	return err
}

func UpdateUser(userId string, u *user.User) error {
	err := db.Db.Model(&user.User{}).Where("user_id = ?", userId).Update(&u).Error
	return err
}

func RegisterUser(u *user.User) (*user.User, error) {

	if UserExists(u) {
		return nil, errors.New("user name or email address already exist")
	}

	salt := uuid.GenerateRandomString()
	userID := uuid.GenUUID()

	u.ID = userID
	u.Password = utils.Encrypt(u.Password, salt, utils.SHA256)
	u.PasswordVersion = utils.SHA256
	u.Salt = salt

	if err := db.Db.Create(&u).Error; err != nil {
		return nil, err
	}
	return GetUser(userID)

}
func LoginUser(u *user.User) (*user.User, error) {

	var user user.User
	err := db.Db.Where("deleted = false and username = ?", u.Username).First(&user).Error

	if err != nil {
		if err == db.ErrRecordNotFound {
			return nil, fmt.Errorf("user name %s not found", u.Username)
		}
		return nil, err
	}

	if !matchPassword(&user, u.Password) {
		return nil, errors.New("The password is incorrect ")
	}

	user.Password = "" // do not return the password
	return &user, nil
}

func ChangeUserPassword(userId string, u *user.User) error {

	u.Salt = uuid.GenerateRandomString()
	u.Password = utils.Encrypt(u.Password, u.Salt, utils.SHA256)

	err := db.Db.Model(&user.User{}).Where("user_id = ?", userId).Update(&u).Error

	return err

}

func IsSuperUser(username string) bool {
	return false
}

func UserExists(u *user.User) bool {

	if u.Username == "" && u.Email == "" {
		return false
	}

	var count int

	db.Db.Model(user.User{}).Where("username = ? || email = ?", u.Username, u.Email).Count(&count)

	if count == 0 {
		return false
	} else {
		return true
	}
}

func matchPassword(u *user.User, password string) bool {
	return utils.Encrypt(password, u.Salt, u.PasswordVersion) == u.Password
}
